package com.garden.web.context.initializer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import javax.servlet.FilterRegistration.Dynamic;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(1)
public class WebAppInitializer implements WebApplicationInitializer {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String CONFIG_LOCATION = "com.garden.web.context.config";
    private static final String MAPPING_URL = "/";

    public void onStartup(ServletContext servletContext) throws ServletException {

        logger.debug("Web Context onStartup...");
        WebApplicationContext context = getContext();

        Dynamic encodingFilter = servletContext.addFilter("EncodingFilter", new CharacterEncodingFilter());
        encodingFilter.setInitParameter("encoding", "UTF-8");
        encodingFilter.setInitParameter("forceEncoding", "true");
        encodingFilter.addMappingForUrlPatterns(null, true, "/*");

        Dynamic simpleCORSFilter = servletContext.addFilter("SimpleCORSFilter", new SimpleCORSFilter());
        simpleCORSFilter.setAsyncSupported(true);
        simpleCORSFilter.addMappingForUrlPatterns(null, true, "/*");

        servletContext.addListener(new ContextLoaderListener(context));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping(MAPPING_URL);
        dispatcher.setMultipartConfig(new MultipartConfigElement(""));


    }

    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation(CONFIG_LOCATION);
        return context;
    }

    public class SimpleCORSFilter implements Filter {
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            response.setHeader("X-Frame-Options", "SAMEORIGIN");
            chain.doFilter(req, res);
        }

        public void init(FilterConfig filterConfig) {
        }

        public void destroy() {
        }
    }
}
